#define  _CRT_SECURE_NO_WARNINGS
#include "SList.h"

SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* node = (SLTNode*)malloc(sizeof(SLTNode));
	assert(node);
	node->data = x;
	node->next = NULL;

	return node;
}

void print(SLTNode* phead)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}


void SLTPushBack(SLTNode** pphead , SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);

	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLTNode* pcur = *pphead;
		while (pcur->next != NULL)
		{
			pcur = pcur->next;
		}
		pcur->next = newnode;
	}
}

void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		SLTNode* tmp = *pphead;
		*pphead = newnode;
		(*pphead)->next = tmp;
	}
}

void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);

	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		SLTNode* pcur = *pphead;
		SLTNode* pre = *pphead;
		while (pcur->next)
		{
			pre = pcur;
			pcur = pcur->next;
		}
		free(pcur);
		pre->next = NULL;
		pcur = NULL;
	}
}

void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);

	SLTNode* tmp = (*pphead)->next;
	free(*pphead);
	*pphead = tmp;
}

SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
{
	assert(phead);
	SLTNode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void SLTInvert(SLTNode** pphead, SLTNode* lo, SLTDataType x)
{
	assert(pphead);
	assert(lo);
	if (*pphead == lo)
	{
		SLTPushFront(pphead, x);
	}
	else
	{
		SLTNode* newnode = SLTBuyNode(x);
		SLTNode* pcur = *pphead;
		while (pcur->next != lo)
		{
			pcur = pcur->next;
		}
		SLTNode* tmp = pcur->next;
		pcur->next = newnode;
		newnode->next = tmp;
	}
}

void SLTInvertBack(SLTNode* find, SLTDataType x)
{
	assert(find);
	SLTNode* newnode = SLTBuyNode(x);
	SLTNode* tmp = find->next;
	find->next = newnode;
	newnode->next = tmp;
}

void SLTErase(SLTNode** pphead, SLTNode* find)
{
	assert(pphead && find);
	if (*pphead == find)
	{
		SLTPopFront(pphead);
	}
	else
	{
		SLTNode* pcur = *pphead;
		while (pcur->next != find)
		{
			pcur = pcur->next;
		}
		pcur->next = find->next;
		free(find);
		find = NULL;
	}
}

void SLTEraseBack(SLTNode* find)
{
	assert(find);
	SLTNode* tmp  = find->next->next;
	free(find->next);
	find->next = tmp;
	
}

void SLTDestroy(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* pcur = *pphead;
	while (pcur)
	{
		SLTNode* tmp = pcur->next;
		free(pcur);
		pcur = tmp;
	}
	*pphead = NULL;
}







